package com.keshan.controller.base;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.keshan.config.MyException;
import com.keshan.service.MdUserServices;
import com.keshan.utils.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 微信相关
 */
@CrossOrigin
@RestController
@RequestMapping("/wx")
public class WxController {

    @Autowired
    private MdUserServices mdUserServices;

    /**
     * @author tangzheng
     * @date 2023/2/11 21:30
     * @description 微信小程序 登录接口
     * @param js_code 微信方用到的code,由前端申请并传回
     * @return com.keshan.utils.Msg
     */
    @RequestMapping("/login")
    public Msg login(String js_code) {
        try {
//            唐铮：的测试小程序配置
            String appid = "wx6e52345f6a48c0a9";
            String secret = "a5dad46686a902ead77abff7751d152d";
//            唐铮：的正式小程序配置
//            String appid = "wxbdf3d4a87199de4f";
//            String secret = "3132733249718034e5ff623e3155e360";
            String grant_type = "authorization_code";
            Map<String, Object> resultMap = JSON.parseObject(HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + js_code + "&grant_type=" + grant_type));
            if (StringUtils.isEmpty(resultMap.get("openid"))) {
                throw new MyException("请求获得openid异常");
            }
            String openid = (String) resultMap.get("openid");
            Map<String, String> user = mdUserServices.doWxLogin(openid);
            return Msg.success().add("user", user);
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }


}
